package com.gz.mylife.im;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Spannable;
import android.text.Spanned;
import android.text.style.DynamicDrawableSpan;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.gz.mylife.Define;
import com.gz.mylife.R;
import com.gz.mylife.app.BaseActivity;
import com.gz.mylife.app.Login;
import com.gz.mylife.im.MessageChannel.Meta;
import com.gz.mylife.widget.ChattingListView;
import com.gz.mylife.widget.EmojiLayout;
import com.gz.mylife.widget.OfflineDialog;
import com.gz.mylife.widget.ChattingListView.OnRefreshListener;
import com.gz.mylife.widget.EmojiLayout.OnEmojiClickListener;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.zl.smartmall.library.account.IAuth;
import com.zl.smartmall.library.util.Constants;
import com.zl.smartmall.library.util.CrashHandler;
import com.zl.smartmall.library.util.PreferenceModel;
import com.zl.smartmall.library.util.SingtonAsyncHttpClient;
import com.zl.smartmall.library.util.Tools;


/**
 * 私信
 *
 */
public class ChatSession extends BaseActivity implements OnClickListener ,OnEmojiClickListener,OnTouchListener,Observer, OnRefreshListener {
	
	private static final String TAG = "ChatSession";
	
	// 发消息状态：正常，发送中，已发送
	public static final int MSG_STATE_NORMAL = 0x00;
	public static final int MST_STATE_SENDING = 0x01;
	public static final int MSG_STATE_FINISH = 0x02;
	
	private String pageSize = "20";

	private ImageView mBtnSend;
	private ImageView mBtnEmoji;
	private ImageView mBtnAdd;

	private EmojiLayout mLayoutEmoji;
	public OfflineDialog mOfflineView;
	private EditText mEditTextContent;
	private ChattingListView mListView;
//	private LoadingEmpty mLoadingEmpty;
//	private FrameLayout mLoading;
	
	private ChatSessionAdapter mAdapter;
	public ChatSessionService mChatService;
	
	private PhotoUtil mPhotoUtil;
	private PhotoUtil.Config mPhotoConfig;
	
	private int mFontSize;
//	private Result mResult;
//	private Userinfo mCurrentUser;  // 当前用户
	private SessionBean mCurrentSession;
	private List<IMessage> mDataList;
//	private UserManager mUserManager;
	private int mSharedDiscuzeId ;
	private int mSharedTopicId;
	private String mSharedTitle;
	private int mType;
	private String mUrl;
	private int mLastId;
	private int fuid;
	private SessionBean mSessionBean;
	
	private AsyncHttpClient mClient;
	
	private int mReqCode = Define.REQ_UNKNOW;
	
	public SessionBean getCurrentSession(){
		return mCurrentSession;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		super.setContentView(R.layout.chatting_msg);
		init(getIntent());
	}
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		init(intent);
	}

	public void init(Intent intent) {
		mFontSize = Tools.dip2px(this.getApplicationContext(),22);
		
		mPhotoUtil = new PhotoUtil(this);
		mPhotoConfig = new PhotoUtil.Config()
		.setIsReturnImage(false)
		.setIsCrop(false)
		.setPhotoCallback(photoCallback);
		
//		mLoading = (FrameLayout) findViewById(R.id.layout_loading);
//		mLoadingEmpty = (LoadingEmpty) mLoading.findViewById(R.id.layout_loading_empty);
		mOfflineView = (OfflineDialog) getLayoutInflater().inflate(R.layout.offline_dialog, null);
		mListView = (ChattingListView) findViewById(R.id.listview1);
//		mListView.setHeadViewBackground(R.drawable.transparent_background);
		//mLoadingEmpty.setOnClickListener(this);
		mListView.setOnRefreshListener(this);
		
		// 表情
		mLayoutEmoji = (EmojiLayout) findViewById(R.id.layout_emoji);
		mLayoutEmoji.setOnEmojiClickListener(this);
		
		mBtnAdd = (ImageView) findViewById(R.id.btn_add);
		mBtnEmoji = (ImageView) findViewById(R.id.btn_emoji);
		mBtnSend = (ImageView) findViewById(R.id.btn_send);
		mEditTextContent = (EditText) findViewById(R.id.et_content);
		mBtnAdd.setOnClickListener(this);
		mBtnEmoji.setOnClickListener(this);
		mBtnSend.setOnClickListener(this);
		mEditTextContent.setOnClickListener(this);
		mEditTextContent.requestFocus();
		
		
		MessageChannel.get().register(MessageChannel.MESSAGE,this);
//		mReceiver01 = new UpdateChatSessionMessage();
//		IntentFilter filter = new IntentFilter(Define.refresh_message_unread);
//		this.registerReceiver(mReceiver01, filter);
		
//		mUserManager = new UserManager(getApplicationContext());
//		mClient = new AsyncHttpClient();
		mClient = SingtonAsyncHttpClient.getInstance();
//		mResult = new Result(this);   
//		mResult.setListView(mListView);
		//mResult.setLoadingEmpty(mLoadingEmpty);
		
		fuid= intent.getIntExtra("fuid",0);
		int gender= intent.getIntExtra("gender",0);
		String nickname = intent.getStringExtra("nickname");
		String face = intent.getStringExtra("face");
		mSharedDiscuzeId = intent.getIntExtra("discuzId", 0);
		mSharedTopicId = intent.getIntExtra("topicId", 0);
		mSharedTitle = intent.getStringExtra("shareTitle");
		mType = intent.getIntExtra("mtype", 1);
		mUrl = intent.getStringExtra("url");
		
//		mCurrentUser = Global.get().getUserinfo();
		mDataList = new ArrayList<IMessage>();
		mCurrentSession = SessionDao.findSession(getApplicationContext(),fuid);
		if(mCurrentSession == null){
			mCurrentSession = new SessionBean();
			mCurrentSession.setFuid(fuid);
			mCurrentSession.setGender(gender);
			mCurrentSession.setNickname(nickname);
			mCurrentSession.setFace(face);
			mCurrentSession.setCurrentUID(IAuth.getInstance().loadUserInfo().getUid());
		} else {
			List<IMessage> messages = MessageDao.getSessionMsgById(getApplicationContext(),  mCurrentSession.getPmid(), -1, 50);
			if (messages != null && messages.size() > 0){
				// 当本地再次打开的时候，校验断层的数据(新的逻辑将不需要在这里检测数据是否断层)
//				int discardId = MessageDao.discardNotConnected(messages);
//				if(discardId > 0){
//					MessageDao.deleteDiscardByLastId(getApplicationContext(), discardId);
//				}
				MessageDao.sort(messages);
				mDataList.addAll(messages);
				MessageDao.filterShowTime(mDataList);
//				mAdapter.notifyDataSetChanged();
			} else {
				RequestParams params = new RequestParams();
				params.put("pmid", mCurrentSession.getPmid()+"");
//				mResult.first(params);
				params.put("flag", "0");
				params.put("lastid", "0");
				params.put("limit", pageSize);
				mReqCode = Result.FIRST;
				mClient.setCookieStore(IAuth.getInstance().loadCookieStore());
				mClient.get(Constants.URL_RECEIVE_IM_MESSAGE, params, new GetAllMessageReponse());
			}
		}
		mAdapter = new ChatSessionAdapter(this,mListView,mDataList);
		mChatService = new ChatSessionService.Builder()
		.setActivity(this)
		.setListView(mListView)
		.setAdapter(mAdapter)
		.setDataList(mDataList)
		.build();
		mListView.setAdapter(mAdapter);
		mListView.setSelection(mAdapter.getCount()-1);
		String nickname2 = "与"+nickname+"聊天中";
//		mActionBar.setTitle(nickname2);
		setActionbarTitle(nickname2, true);
		if(mDataList.size()>0){
			checkIsConnect(mDataList);
			mChatService.getUnReceived(mDataList.get(mDataList.size()-1));//获取离线消息
		}
	}

	private void checkIsConnect(List<IMessage> lists) {
		if(lists == null ){
			return;
		}
		for(int i = 0;i<lists.size();i++){
			mChatService.isConnect(lists.get(i));
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		PreferenceModel.putInt(Define.PREFERENCE_KEY_CHAT_SESSION_NOTIFICATION, fuid);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		PreferenceModel.putInt(Define.PREFERENCE_KEY_CHAT_SESSION_NOTIFICATION, 0);
		
		mCurrentSession = SessionDao.findSession(getApplicationContext(),fuid);
		if(mCurrentSession != null){
			int count = PreferenceModel.getInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
			count =count -mCurrentSession.getUnreadCount();
			if(count > 0){
				PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, count);
			} else {
				PreferenceModel.putInt(Define.PREFERENCE_KEY_UNREAD_IM_COUNT, 0);
			}
			mCurrentSession.setUnreadCount(0);
			SessionDao.update(getApplicationContext(), mCurrentSession);
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) { 
//		getMenuInflater().inflate(R.menu.chat_session, menu);
//		MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_user_profile), MenuItemCompat.SHOW_AS_ACTION_ALWAYS);

		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()){
		case android.R.id.home:
			finish();
			return true;
			
		case R.id.action_user_profile:
//			if(fuid == IAuth.getInstance().loadUserInfo().getUid()){
//				Intent intent = new Intent();
//				intent.setClass(getApplicationContext(), MyProfileSelf.class);
//				intent.putExtra("fuid", fuid);
//				startActivity(intent);
//			}else{
//				Intent intent = new Intent();
//				intent.setClass(getApplicationContext(), MyProfileOther.class);
//				intent.putExtra("fuid", fuid);
//				startActivity(intent);
//			}
			return true;
			
		default:
			return super.onOptionsItemSelected(item);
		}
	}
	
	@Override
	public void onRefresh() {
			List<IMessage> messages = mDataList.size()>0?MessageDao.getSessionMsgById(getApplicationContext(),  mCurrentSession.getPmid(), mDataList.get(0).getId(), 50):null;
			if(messages != null&&messages.size()>0){
				CrashHandler.d(TAG, "messages :"+messages.size());
				MessageDao.sort(messages);
//				mDataList.addAll(messages);
//				Collections.sort(mDataList, mComparator);
				checkIsConnect(messages);
				mDataList.addAll(0, messages);
				mAdapter.notifyDataSetChanged();
				mListView.onRefreshComplete();
			}else{
//				CrashHandler.d(TAG, "messages is null");
//				mLastId = Integer.MAX_VALUE;
//				for(int i = 0;i<mDataList.size();i++){
//					int lastid = mDataList.get(i).getLastid();
//					if(lastid < mLastId){
//						mLastId = lastid;
//					}
//				}
//				if(hasNext() && mCurrentSession.getPmid() > 0){
//					RequestParams params = new RequestParams();
//					params.put("pmid", mCurrentSession.getPmid()+"");
//					mResult.pull(params);
//					params.put("flag", "1");
//					params.put("lastid", mLastId+"");
//					mClient.setCookieStore(Global.get().getCookie());
//					mClient.get(Define.secret_sms_get_v3, params, new GetAllMessageReponse());
//					} else {
//						mListView.onRefreshComplete();
//				}
				mListView.onRefreshComplete();
			}
		
	}
	
	
	boolean hasNext(){
		if(mDataList.size() ==0){
			return false;
		}
		return mDataList.get(0).getLastid() > 1;
	}
	
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		MessageChannel.get().unregister(MessageChannel.MESSAGE,this);
		if(mChatService != null){
			mChatService.destory();
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if(mPhotoUtil!=null){
			mPhotoUtil.onActivityResult(requestCode, resultCode, data);
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_send:
			if(IAuth.getInstance().isUserValid()) {
				String content = mEditTextContent.getText().toString();
				mEditTextContent.getText().clear();
				if (content.length() > 0) {
					mChatService.sendTextMessage(mCurrentSession.getPmid(),mCurrentSession.getFuid(), content);
				} else {
					Toast.makeText(ChatSession.this, "内容不能为空", Toast.LENGTH_LONG).show();
				}
			} else {
				startActivity(new Intent(getApplicationContext(), Login.class));
			}
			
			break;
		case R.id.btn_add:
			if(IAuth.getInstance().isUserValid()) {
				if (mLayoutEmoji.getVisibility() == View.VISIBLE) {
					mLayoutEmoji.setVisibility(View.GONE);
				}
				InputMethodManager mInputMethod = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
				if(mInputMethod.isActive()) {
					mInputMethod.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), 0);
				}
				mPhotoUtil.setTitle("添加照片");
				mPhotoUtil.takePhoto(mPhotoConfig);
				
			} else {
				startActivity(new Intent(getApplicationContext(), Login.class));
			}
			break;
			
		case R.id.btn_emoji:
			InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			if (mLayoutEmoji.getVisibility() == View.VISIBLE) {
				mLayoutEmoji.setVisibility(View.GONE);
			} else {
				mLayoutEmoji.getSmile().performClick();
				mLayoutEmoji.setVisibility(View.VISIBLE);
				getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
				// 隐藏软键盘
				mInputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getApplicationWindowToken(), 0);
			}
			break;
		case R.id.et_content:
			mLayoutEmoji.setVisibility(View.GONE);
			getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
									| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
			break;
//		case R.id.layout_loading_empty:
//			RequestParams params = new RequestParams();
//			params.put("pmid", mCurrentSession.getPmid()+"");
//			mResult.first(params);
//			mClient.setCookieStore(Global.get().getCookie());
//			mClient.get(Define.secret_sms_get_v3, params, new GetAllMessageReponse());
//			break;
		}
	}
	
	@Override
	public boolean onTouch(View v, MotionEvent event) {
		if (mLayoutEmoji.getVisibility() == View.VISIBLE) {
			mLayoutEmoji.setVisibility(View.GONE);
		}
		return false;
	}
	
	@Override
	public boolean onKeyDown(int arg0, KeyEvent arg1) {
		if(arg1.getKeyCode()==KeyEvent.KEYCODE_BACK){
//			if(mOfflineView.isShowing()){
//				return mOfflineView.onKeyDown(arg0, arg1);
//			}
			
			if(mLayoutEmoji.getVisibility()==View.VISIBLE){
				mLayoutEmoji.setVisibility(View.GONE);
				return true;
			}
			if(mPhotoUtil.isShow()){
				mPhotoUtil.hideSelectView();
				return true;
			}
			
//			finish();
//			return true;
		}
		return super.onKeyDown(arg0, arg1);
	}
	
	@Override
	public void onEmojiDeleteClick() {
		if(mEditTextContent.isFocused()){
			mEditTextContent.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
		}
	}

	@Override
	public void onEmojiClick(int emojiResourceId) {
		if(mEditTextContent.isFocused()){
			setFace(mEditTextContent, emojiResourceId);
		}
	}
	
	private void setFace(EditText edit, int emojiResource) {
		int start = edit.getSelectionStart();//获取光标位置
		String emojiTitle = getResources().getResourceName(emojiResource).split("/")[1];//ef0011ef
		Spannable ss = edit.getText().insert(start, "<" + emojiTitle + ">");
		Drawable d = getResources().getDrawable(emojiResource);

		d.setBounds(0, 0, mFontSize, mFontSize);
		ImageSpan span = new ImageSpan(d, emojiTitle + ".gif",DynamicDrawableSpan.ALIGN_BOTTOM);
		ss.setSpan(span, start, start + ("<" + emojiTitle + ">").length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
	}
	
	
	void hideInputMethod(){
		InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
		if(imm.isActive(mEditTextContent)){
			imm.hideSoftInputFromWindow(mEditTextContent.getWindowToken(), 0);
		}
	}
	
	class GetAllMessageReponse extends JsonHttpResponseHandler{
		
		@Override
		public void onStart() {
		}

//		@Override
//		protected Object parseResponse(String responseBody)throws JSONException {
//			//Log.e("content", "responseBody");
//			Object object = super.parseResponse(responseBody);
//			if(object instanceof JSONObject){
//				JSONObject response = (JSONObject) object;
//				int ret = response.getInt("ret");
//				if(ret == 0){
//					JSONObject result = response.getJSONObject("result");
//					List<IMessage> data = MessageDao.adapter(result.getJSONArray("data"));
//					MessageDao.sortResponse(data);
//					if(mReqCode == Result.FIRST){
//						MessageDao.save(getApplicationContext(), data);
//						mDataList.clear();
//						mDataList.addAll(data);
//					} else {
//						MessageDao.save2(getApplicationContext(), data);
////						mDataList.addAll(0,data);
//						Tools.merge(mDataList, data, mComparator);
//						Collections.sort(mDataList, mComparator);
//					}
//					MessageDao.filterShowTime(mDataList);
//				}
//			} 
//			return object;
//		}
		
		
		@Override
		public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
			try {
//				int ret = response.getInt("ret");
//				if(ret == 0){
//					mAdapter.notifyDataSetChanged();
//					if(mSharedDiscuzeId != 0 && mSharedTopicId != 0){
////						Toast.makeText(getApplicationContext(), "分享："+mSharedDiscuzeId+":"+mSharedTopicId+":"+mSharedTitle, 1).show();
//						mChatService.sendshareMessage(mUrl,mType,mCurrentSession.getPmid(),mCurrentSession.getFuid(),mSharedTitle, mSharedDiscuzeId, mSharedTopicId);
//					}
//				}
				int ret = response.getInt("ret");
				if(ret == 0){
					JSONObject result = response.getJSONObject("result");
					List<IMessage> data = MessageDao.adapter(result.getJSONArray("data"));
					MessageDao.sortResponse(data);
					if(mReqCode == Result.FIRST){
						MessageDao.save(getApplicationContext(), data);
						mDataList.clear();
						mDataList.addAll(data);
					} else {
						MessageDao.save2(getApplicationContext(), data);
//						mDataList.addAll(0,data);
						Tools.merge(mDataList, data, mComparator);
						Collections.sort(mDataList, mComparator);
					}
					MessageDao.filterShowTime(mDataList);
					mAdapter.notifyDataSetChanged();
				}
				
			} catch (JSONException e) {
				CrashHandler.e(e);
			}
			
		}
		
		@Override
		public void onFinish() {
		}
	}
	
	Comparator<IMessage> mComparator = new Comparator<IMessage>(){
		@Override
		public int compare(IMessage arg0, IMessage arg1) {
			if(arg0.getId() > arg1.getId()){
				return 1;
			} else if(arg0.getId() < arg1.getId()){
				return -1;
			} else {
				return 0;
			}
		}
	};
	
	@Override
	public void update(Observable observable, Object data) {
		Meta meta = (Meta) data;
		if(meta.msgType == MessageChannel.MESSAGE){
			IMessage message = (IMessage) meta.data;
			if(mCurrentSession.getPmid() == 0){
				SessionBean session = SessionDao.findSession(getApplicationContext(),mCurrentSession.getFuid());
				mCurrentSession.setPmid(session.getPmid());
			}
			if(message.getPmid() == mCurrentSession.getPmid()){
				if(!mDataList.contains(message)){
					mDataList.add(message);
//					int notConnected = MessageDao.discardNotConnected(mDataList);
//					if(notConnected > 0){
//						mAdapter.notifyDataSetChanged();
//					} else {
//						mListView.setSelection(mListView.getBottom());
//					}  //原来的是否连续的判断
					mListView.setSelection(mListView.getBottom());
					mChatService.isConnect(message);
				}
			}
		}
	}
	
//	private class UpdateChatSessionMessage extends BroadcastReceiver {
//		@Override
//		public void onReceive(final Context context, Intent intent) {
//			IMessage message = intent.getParcelableExtra("message");
//			if(!mDataList.contains(message)){
//				mDataList.add(message);
//				mListView.setSelection(mListView.getBottom());
//			}
//		}
//	}
	
	PhotoUtil.PhotoCallback photoCallback = new PhotoUtil.PhotoCallback() {
		@Override
		public void onBack(Bitmap bitmap, String path) {
			mChatService.sendPhotoMessage(mCurrentSession.getPmid(),mCurrentSession.getFuid(), path);
		}
	};


}